import axios from "axios";
import { Message, Loading } from "element-ui";
// import router from "@/config/PageRoutes";
import Cookies from "js-cookie";
import { generateSign } from "vinehoo-v3-api-sign";
let loadingCount = 0;
function addLoading() {
    Loading.service({
        lock: true,
        fullscreen: true,
        text: "技术小哥正在拼命加载中",
        background: "Transparent"
    });
    loadingCount++;
}
function isCloseLoading() {
    loadingCount--;
    if (loadingCount === 0) {
        Loading.service().close();
    }
}
axios.interceptors.request.use(
    config => {
        addLoading();
        let token = Cookies.get("token");
        let uid = Cookies.get("uid");
        let userinfo = localStorage.getItem("userinfo")
            ? localStorage.getItem("userinfo")
            : {};
        try {
            userinfo = JSON.parse(userinfo);
        } catch {
            console.log("err");
        }
        config.headers = {
            ...generateSign(config, token),
            ...config.headers,
            "dingtalk-uid": userinfo.dt_userid ? userinfo.dt_userid : "",
            "dingtalk-dept-id": userinfo.dept_id ? userinfo.dept_id : "",

            "vinehoo-client": "vos-" + window.location.pathname.split("/")[1],
            "vinehoo-client-version": window.localStorage.getItem(
                `/${window.location.pathname.split("/")[1]}`
            )
                ? window.localStorage.getItem(
                      `/${window.location.pathname.split("/")[1]}`
                  )
                : "0.0.0",
            "access-token": token ? token : "",
            "vinehoo-uid": uid ? uid : ""
        };
        return config;
    },
    error => {
        return Promise.reject(error.response);
    }
);

axios.interceptors.response.use(
    response => {
        isCloseLoading();
        if (response.data.error_code != 0) {
            Message.error(response.data.error_msg);
            switch (response.data.error_code) {
                case 401:
                    // 没有登陆 or token失效
                    setTimeout(() => {
                        window.location.replace("/login/login");
                        Cookies.remove("token");
                        Cookies.remove("uid");
                    }, 1200);
                    break;
            }
        }
        return response;
    },
    error => {
        Loading.service().close();
        if (error.response.status) {
            switch (error.response.status) {
                case 500:
                    Message.error(
                        "TaT ,我们的程序员好像出小差了 , 请联系客服 (服务状态码 500）"
                    );
                    break;
                default:
                    Message.error("系统异常");
                    break;
            }
            return Promise.reject(error.response);
        }
    }
);
